package com.jpress.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public abstract class GeralUtils {

	public static String criptografar(String frase, String algoritmo) {
		try {
			MessageDigest md = MessageDigest.getInstance(algoritmo);
			BigInteger hash = new BigInteger(1, md.digest(frase.getBytes()));
			return hash.toString(16);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
	
	public static String gerarSenha(int tamanho){
		String caracteres = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String senha = "";
		int x;
		
		tamanho = Math.min(2500, tamanho);
		for (int i = 0; i < tamanho; i++) {
			x = (int) (Math.random() * (caracteres.length() - 1)); 
			senha += caracteres.charAt(x);
		}
		return senha;
	}
	
	public static String removerMascara(String string){
		return string.replaceAll("[^0-9]", "");
	}
	
    public static String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();
 
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {        
            return "";
        }
    }
}
